# Contributor: Eric Molitor <eric@molitor.org>
# Contributor: Jakub Jirutka <jakub@jirutka.cz>
# Contributor: Rasmus Thomsen <oss@cogitri.dev>
# Maintainer: Natanael Copa <ncopa@alpinelinux.org>
pkgname=lld
pkgver=19.1.2
pkgrel=0
_llvmver=${pkgver%%.*}
pkgdesc="The LLVM Linker"
url="https://llvm.org/"
# ld.lld: error: src/gn/gn_main.o: could not infer e_machine
# from bitcode target triple s390x-alpine-linux-musl
arch="all !s390x"
license="Apache-2.0"
depends_dev="$pkgname=$pkgver-r$pkgrel"
makedepends="
	clang
	cmake
	compiler-rt
	libedit-dev
	libxml2-dev
	llvm$_llvmver-dev
	llvm$_llvmver-gtest
	llvm$_llvmver-static
	llvm$_llvmver-test-utils
	llvm-libunwind-dev
	patchelf
	samurai
	scudo-malloc~$_llvmver
	zlib-dev
	"
checkdepends="gtest-dev bash llvm$_llvmver-test-utils"
subpackages="$pkgname-dbg $pkgname-libs $pkgname-dev $pkgname-doc"
source="https://github.com/llvm/llvm-project/releases/download/llvmorg-${pkgver//_/-}/lld-${pkgver//_/}.src.tar.xz
	https://github.com/llvm/llvm-project/releases/download/llvmorg-${pkgver//_/-}/cmake-${pkgver//_/}.src.tar.xz
	"
builddir="$srcdir/$pkgname-${pkgver//_/}.src"

prepare() {
	default_prepare
	mv "$srcdir"/cmake-${pkgver//_/}.src "$srcdir"/cmake
}

build() {
	local lit=/usr/lib/llvm$_llvmver/bin/lit
	local cflags="$CFLAGS"
	local cxxflags="$CXXFLAGS"
	case "$CARCH" in
	aarch64|arm*|riscv64|loongarch64)
		# not supported by clang here
		cflags="${cflags/-fstack-clash-protection}"
		cxxflags="${cxxflags/-fstack-clash-protection}"
		;;
	esac

	CFLAGS="$cflags -O2 -DNDEBUG -g1" \
	CXXFLAGS="$cxxflags -O2 -DNDEBUG -g1" \
	CC=clang CXX=clang++ \
	cmake -B build -G Ninja -Wno-dev \
		-DCMAKE_BUILD_TYPE=None \
		-DCMAKE_INSTALL_PREFIX=/usr \
		-DCMAKE_SKIP_INSTALL_RPATH=ON \
		-DBUILD_SHARED_LIBS=ON \
		-DLLVM_INCLUDE_TESTS="$(want_check && echo ON || echo OFF)" \
		-DLLVM_EXTERNAL_LIT=$lit \
		-DLLD_BUILT_STANDALONE=ON \
		-DCMAKE_EXE_LINKER_FLAGS="$LDFLAGS -Wl,-z,stack-size=2097152"
	cmake --build build
}

check() {
	ninja -C build check-lld
}

package() {
	DESTDIR="$pkgdir" cmake --install build
	install -Dm644 "$builddir"/docs/ld.lld.1 -t "$pkgdir"/usr/share/man/man1/

	# we have the scudo allocator available, so link lld to it to
	# significantly improve performance, especially in LTO contexts
	patchelf --add-needed libscudo.so "$pkgdir"/usr/bin/lld
}

sha512sums="
8e89ea4ac78e1a2b303aafac74b99c8f78ef1a3ba13358f845367f45321c701e6ddd969af8b5473a876e8fcba8480600113fbeb7a2a7ac0b8d209bc524348c3c  lld-19.1.2.src.tar.xz
9d13575a3e55a500dd5370591386a79ccc2164056448571620427f64236bf3fd1369090e3d5bdeef725b181d563462f331ff03c54e0667c01d079cf3af8b0c3f  cmake-19.1.2.src.tar.xz
"
